import * as yaml from 'js-yaml';
import { YAMLError, ValidationResult } from '../types';

/**
 * 解析YAML字符串
 */
export function parseYAML(yamlString: string): any {
  try {
    return yaml.load(yamlString);
  } catch (error) {
    console.error('YAML解析错误:', error);
    return null;
  }
}

/**
 * 将对象转换为YAML字符串
 */
export function stringifyYAML(object: any): string {
  try {
    return yaml.dump(object, {
      indent: 2,
      lineWidth: 120,
      noRefs: true
    });
  } catch (error) {
    console.error('YAML序列化错误:', error);
    return '';
  }
}

/**
 * 验证YAML语法
 */
export function validateYAML(yamlString: string): ValidationResult {
  const result: ValidationResult = {
    isValid: true,
    errors: [],
    warnings: [],
    lastValidated: new Date()
  };

  try {
    yaml.load(yamlString);
  } catch (error: any) {
    result.isValid = false;
    
    const yamlError: YAMLError = {
      line: error.mark?.line + 1 || 1,
      column: error.mark?.column + 1 || 1,
      message: error.message || '未知错误',
      severity: 'error'
    };
    
    result.errors.push(yamlError);
  }

  return result;
}

/**
 * 格式化YAML内容
 */
export function formatYAML(yamlString: string): string {
  try {
    const parsed = yaml.load(yamlString);
    return yaml.dump(parsed, {
      indent: 2,
      lineWidth: 120,
      noRefs: true,
      sortKeys: false
    });
  } catch (error) {
    console.error('YAML格式化错误:', error);
    return yamlString; // 返回原始内容
  }
}

/**
 * 检查YAML内容是否为空
 */
export function isEmptyYAML(yamlString: string): boolean {
  const trimmed = yamlString.trim();
  return trimmed === '' || trimmed.startsWith('#') && !trimmed.includes(':');
}

/**
 * 获取YAML文档的基本信息
 */
export function getYAMLInfo(yamlString: string) {
  const lines = yamlString.split('\n');
  const nonEmptyLines = lines.filter(line => line.trim() !== '');
  const commentLines = lines.filter(line => line.trim().startsWith('#'));
  
  let keys = 0;
  let depth = 0;
  let type = 'unknown';
  
  try {
    const parsed = parseYAML(yamlString);
    if (parsed !== null) {
      // 计算键的数量和最大深度
      const countKeysAndDepth = (obj: any, currentDepth = 0): { keys: number; maxDepth: number } => {
        if (obj === null || typeof obj !== 'object') {
          return { keys: 0, maxDepth: currentDepth };
        }
        
        let totalKeys = 0;
        let maxDepth = currentDepth;
        
        if (Array.isArray(obj)) {
          obj.forEach(item => {
            const result = countKeysAndDepth(item, currentDepth + 1);
            totalKeys += result.keys;
            maxDepth = Math.max(maxDepth, result.maxDepth);
          });
        } else {
          Object.keys(obj).forEach(key => {
            totalKeys += 1;
            const result = countKeysAndDepth(obj[key], currentDepth + 1);
            totalKeys += result.keys;
            maxDepth = Math.max(maxDepth, result.maxDepth);
          });
        }
        
        return { keys: totalKeys, maxDepth };
      };
      
      const result = countKeysAndDepth(parsed);
      keys = result.keys;
      depth = result.maxDepth;
      
      // 确定数据类型
      if (Array.isArray(parsed)) {
        type = 'array';
      } else if (typeof parsed === 'object') {
        type = 'object';
      } else {
        type = typeof parsed;
      }
    }
  } catch (error) {
    // 解析失败时保持默认值
  }
  
  return {
    totalLines: lines.length,
    nonEmptyLines: nonEmptyLines.length,
    commentLines: commentLines.length,
    size: new Blob([yamlString]).size,
    keys,
    depth,
    type
  };
}